package cn.jy.careuplusdoctor.main;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Timer;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import cn.jy.careuplusdoctor.R;
import cn.jy.careuplusdoctor.base.BaseActivity;
import cn.jy.careuplusdoctor.http.HttpHelper;
import cn.jy.careuplusdoctor.http.HttpHelper.onHttpListener;
import cn.jy.careuplusdoctor.http.HttpUrls;
import cn.jy.careuplusdoctor.injector.IdInject;
import cn.jy.careuplusdoctor.mycenter.HospitalListActivity;
import cn.jy.careuplusdoctor.response.LoginResponse;
import cn.jy.careuplusdoctor.response.SendMassageResponse;
import cn.jy.careuplusdoctor.utils.Code;
import cn.jy.careuplusdoctor.utils.DesTool4Android;
import cn.jy.careuplusdoctor.utils.StringUtil;
import cn.jy.careuplusdoctor.widgets.CareuTitleBar.TitleBarLeftAction;
import cn.jy.careuplusdoctor.widgets.CareuTitleBar.TitleBarRightAction;
import fay.frame.fast.F;

public class RegisterActivity extends BaseActivity implements TitleBarRightAction,TitleBarLeftAction{
	
	@IdInject(id=R.id.edit_phoneNum)
	private EditText edit_phoneNum;
	@IdInject(id=R.id.code_nyum)
	private EditText code_nyum;
	@IdInject(id=R.id.reg_password)
	private EditText reg_password;
	@IdInject(id=R.id.reg_password01)
	private EditText confirm_password;
	@IdInject(id=R.id.edit_fullname)
	private EditText edit_fullname;
	@IdInject(id=R.id.reg_sex)
	private EditText reg_sex;
	@IdInject(id=R.id.reg_mail)
	private EditText reg_mail;
	@IdInject(id=R.id.edit_hospital)
	private EditText edit_hospital;
	@IdInject(id=R.id.edit_section_office)
	private EditText edit_section_office;
	@IdInject(id=R.id.edit_job_title)
	private EditText edit_job_title;
	@IdInject(id=R.id.edit_certificate)
	private EditText edit_certificate;
	@IdInject(id=R.id.reg_button_info)
	private Button   reg_button_info;
	@IdInject(id=R.id.checkcode_button)
	private Button   checkcode_button;
	@IdInject(id=R.id.img_certificate)
	private ImageView    img_certificate; 
	
	ArrayList<EditText> _list= new ArrayList<EditText>();
	private boolean flag = false;
	private TimeCount time;
	Timer timer;
	String  checknum;
	private String phone,password,cPassword,dName,sex,licenceCode,hid,qHospital,sid,qSubject,medicalTitle,email,licencePicUrl;
	private String sexStr = "";
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		
		initTitleBar();
		time = new TimeCount(60000, 1000);
		Code.getInstance().createBitmap();
		onInJectView();
		notEdit();
		
	}
	
	@Override
	protected void onAfterInJector() {
		super.onAfterInJector();
		
		_list.add(reg_password);
		_list.add(confirm_password);
		_list.add(edit_fullname);
		_list.add(reg_sex);
		_list.add(reg_mail);
		_list.add(edit_hospital);
		_list.add(edit_section_office);
		_list.add(edit_job_title);
		_list.add(edit_certificate);
		_list.add(reg_password);
		
		OnClickListener listener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.checkcode_button:
					checkNum();
					break;
				case R.id.reg_button_info:
					reg();
					break;
				}
			}
		};
		findViewById(R.id.checkcode_button).setOnClickListener(listener);
		findViewById(R.id.reg_button_info).setOnClickListener(listener);
		findViewById(R.id.edit_certificate).setOnClickListener(listener);
		
		
		code_nyum.addTextChangedListener(new CodeEditChanged());
		
		edit_certificate.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					startActivityForResult(new Intent(RegisterActivity.this, LicenceActivity.class),  1001);
				}
				return true;
			}
		});
		
		edit_hospital.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					Intent i = new Intent(RegisterActivity.this, HospitalListActivity.class);
					i.putExtra("ListString", "医院");
					startActivityForResult(i, 1001);
				}
				return true;
			}
		});
		
		edit_section_office.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					if(hid!=null){
						Intent i = new Intent(RegisterActivity.this, HospitalListActivity.class);
						i.putExtra("ListString", "科室");
						i.putExtra("hid", hid);
						startActivityForResult(i, 1001);
					}else{
						shortToast("请先选择医院");
					}
				}
				return true;
			}
		});
		
		reg_sex.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					Dialog dialog = null;
					Builder sexbuilder = new AlertDialog.Builder(RegisterActivity.this);
					sexbuilder.setIcon(R.drawable.zhuce9);
					sexbuilder.setTitle("性别");
					final ChoiceOnClickListener sexchoiceListener = new ChoiceOnClickListener();
					sexbuilder.setSingleChoiceItems(R.array.sex, 0, sexchoiceListener);

					DialogInterface.OnClickListener sexbtnListener = new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialogInterface, int which) {

							int choiceWhich = sexchoiceListener.getWhich();
							String hobbyStr = getResources().getStringArray(R.array.sex)[choiceWhich];
							reg_sex.setText(hobbyStr);
						}
					};
					sexbuilder.setPositiveButton("确定", sexbtnListener);
					dialog = sexbuilder.create();
					dialog.show();
				}
				return true;
			}
		});
		
	}
	
	/**
	 * 用户注册
	 */
	protected void reg() {
		
		
		
		phone = edit_phoneNum.getText().toString().trim();
		password = reg_password.getText().toString().trim();
		cPassword=confirm_password.getText().toString().trim();
		dName = edit_fullname.getText().toString().trim();
		sex = reg_sex.getText().toString().trim();
		licenceCode=edit_certificate.getText().toString().trim();
		qHospital=edit_hospital.getText().toString().trim();
		qSubject=edit_section_office.getText().toString().trim();
		medicalTitle=edit_job_title.getText().toString().trim();
		email=reg_mail.getText().toString().trim();
		
		
		
		if("男".equals(reg_sex.getText().toString().trim())){
			sexStr="0";
		}else if("女".equals(reg_sex.getText().toString().trim())){
			sexStr="1";
		}
		
		if(!StringUtil.isNotEmpty(phone)||!StringUtil.isNotEmpty(password)||!StringUtil.isNotEmpty(cPassword)
				||!StringUtil.isNotEmpty(dName)||!StringUtil.isNotEmpty(sex)||!StringUtil.isNotEmpty(licenceCode)
				||!StringUtil.isNotEmpty(qHospital)||!StringUtil.isNotEmpty(qSubject)
				||!StringUtil.isNotEmpty(email)){
			shortToast("请把信息补充完整");
		}else if (!StringUtil.isEmail(email)) {
			shortToast("正确填写邮箱格式");
		}else if(email.trim().length()>50){
			shortToast("邮箱不能超过50个字符");
		}else if(medicalTitle.trim().length()>50){
			shortToast("职称不能超过50个字符");
		}else if (password.equals(cPassword) == false) {
			shortToast("两次输入的密码不相同");
		}else if ("".equals(phone) || null == (phone)
				|| ("".equals(password) || null == password)
				|| ("".equals(cPassword) || null == cPassword)) {
			shortToast("账号或密码不能为空");
		}  else if ((password.trim()).length() < 6 || password.length() > 20) {
			shortToast("密码长度不能少于6位且不超过20位");
		}else {
			showLoading("正在提交");
			HttpHelper.getInstance().reg(phone, password, dName, sexStr, licenceCode, hid,qHospital, sid,qSubject, medicalTitle, email, licencePicUrl, new onHttpListener<LoginResponse>() {
				
				@Override
				public void onResponse(LoginResponse data, int code) {
					hidenLoading();
					if (data !=null && code == HttpUrls.REQUEST_SUCCESS) {
						if (TextUtils.equals("0", data.getResType())) {
							shortToast("注册成功");
							openActivity(LoginActivity.class);
							defaultFinish();
						}
						else {
							shortToast(data.getMsg());
						}
					}
					else {
						shortToast(R.string.login_fail_reason1);
					}
				}
			});
		}
		
		
	}

	/**
	 * 检查号码是否正确
	 */
	protected void checkNum() {
		String registerNum;
		registerNum = edit_phoneNum.getText().toString().trim();
		if (registerNum.equals("")) {
			shortToast("请输入手机号");
		} else {
			flag = StringUtil.isMobile(registerNum);
			if (flag == false) {
				shortToast("手机号不合法");
			} else {
				time.start();
				sendMessage();
			}
		}
	}

	/**
	 * 发送短信
	 */
	private void sendMessage() {
		String tokenStr = "";

		checknum = Code.getInstance().getCode().toString();
		try {
			tokenStr=DesTool4Android.getToken(edit_phoneNum.getText().toString().trim(),checknum );
		} catch (Exception e) {
			e.printStackTrace();
		}
		String content = "尊敬的用户，您正在注册成为慢糖生活APP会员,注册验证码:："+ checknum + "【广州嘉祐】";
		
		
		
		try {
			HttpHelper.getInstance().sendMessage(URLEncoder.encode(tokenStr,"UTF-8"), content, new onHttpListener<SendMassageResponse>() {
				
				@Override
				public void onResponse(SendMassageResponse data, int code) {
					if (data !=null && code == HttpUrls.REQUEST_SUCCESS) {
						if (TextUtils.equals("1", data.getResType())) {
						}
						else {
							shortToast(data.getMsg());
						}
					}
					else {
						shortToast(R.string.login_fail_reason1);
					}
				}
			});
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	protected void settingTitleBar() {
		// TODO Auto-generated method stub
		super.settingTitleBar();
		
		getTitleBar().setLeftText("取消");
		getTitleBar().setTitle("注册");
		getTitleBar().setRightText("完成");
		getTitleBar().setLeftAction(this);
		getTitleBar().setRightAction(this);
		getTitleBar().getLeftImageView().setVisibility(View.GONE);
		getTitleBar().getRightImageView().setVisibility(View.GONE);
		
	}
	@Override
	public void onLeftPress(View view) {
		defaultFinish();
		
	}
	@Override
	public void onRightPress(View view) {
		reg();
	}
	
	/**
	 * 资料输入框不可编辑
	 */
	private void notEdit(){
		for(EditText t : _list){
			t.setFocusableInTouchMode(false);
			t.setEnabled(false);
			t.requestFocus();
			//t.setOnTouchListener(null);
		}
	}
	/**
	 * 资料输入框可编辑
	 */
	private void edit(){
		for(EditText t : _list){
			t.setFocusableInTouchMode(true);
			t.setEnabled(true);
			t.requestFocus();
		}
	}
	
	class TimeCount extends CountDownTimer {

		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			checkcode_button.setClickable(false);
			edit_phoneNum.setEnabled(false);
			edit_phoneNum.setFocusable(false);
			checkcode_button.setText(millisUntilFinished / 1000 + "秒后再次发送");
			
		}
		
		@Override
		public void onFinish() {
			checkcode_button.setText("验证码");
			edit_phoneNum.setEnabled(true);
			edit_phoneNum.setFocusable(true);
			checkcode_button.setClickable(true);

		}
	}
	
	/**
	 * 验证码监听器
	 * @author YAO
	 *
	 */
	class CodeEditChanged implements TextWatcher{

		@Override
		public void afterTextChanged(Editable editable) {
		}

		@Override
		public void beforeTextChanged(CharSequence charsequence, int i, int j,
				int k) {
		}

		@Override
		public void onTextChanged(CharSequence charsequence, int i, int j, int k) {
			/**
			 * 验证码为6位数
			 */
			if(charsequence.length()==6){
				if(checknum!=null){
					if(checknum.equals(charsequence.toString())){
						time.cancel();
						checkcode_button.setClickable(false);
						edit_phoneNum.setEnabled(false);
						edit_phoneNum.setFocusable(false);
						checkcode_button.setText("校对成功");
						edit();
					}
				}
			}	
		}
	}
	
	private class ChoiceOnClickListener implements DialogInterface.OnClickListener {

			private int which = 0;
			
			@Override
			public void onClick(DialogInterface dialogInterface, int which) {
				this.which = which;
			}
			
			public int getWhich() {
				return which;
			}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode==1001){
			Bundle b=data.getExtras(); 
			edit_certificate.setText(b.getString("licenceNum"));
			String url = b.getString("url");
			String _url = "http://www.careuplus.net:8991"+url;
			licencePicUrl = url;
			F f = new F(RegisterActivity.this);
			f.id(img_certificate).image(_url);
		}else if(resultCode==1002){
			Bundle b=data.getExtras(); 
			edit_hospital.setText(b.getString("name"));
			hid=b.getString("id");
		}else if(resultCode==1003){
			Bundle b=data.getExtras(); 
			edit_section_office.setText(b.getString("name"));
			sid=b.getString("id");
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
}
